import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type { SystemPostDataItemType, SystemPostStateType } from './typings'
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElIcon,
  ElCard,
  ElFormItem,
  ElSelect,
  ElOption,
  ElInput,
  ElButton,
  ElLink,
  ElMessageBox,
  ElMessage
} from 'element-plus'
import { View, EditPen, Delete, Plus } from '@element-plus/icons-vue'
import type { categoryEnum } from '~/store/system/typings'
import { cloneDeep } from 'lodash'
import { handleTrim } from '~/utils/util'
import ProSaasTable from '~/components/ProSaasTable'
import SearchForm from '~/components/ProForm/SearchForm'
import useVuexGetters from '~/hooks/useVuexGetters'
import SystemPostOptionsModal from './options'

export default defineComponent(function SystemPost() {
  const store = useStore()
  // 初始值
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const formValues = reactive<SystemPostDataItemType>({})
  const state = reactive<SystemPostStateType>({
    modalVisible: false,
    type: 'read',
    record: {}
  })

  const systemPostState = useVuexGetters('systemPost', [
    'categorySelectList',
    'categoryEnum',
    'tenantSelectEnum'
  ])
  const orderState = useVuexGetters('order', [
    // 是/否
    'appointmentTimeEnum'
  ])
  const userState = useVuexGetters('user', ['permission'])

  onMounted(async () => {
    store.dispatch('systemPost/GetTenantSelect') // 所属租户
    getCategoryDictAjax() // 岗位类型
  })

  // methods
  // 岗位类型
  const getCategoryDictAjax = () => {
    store.dispatch('systemPost/GetDataDictionaryByCode', { code: 'post_category' })
  }

  // 操作列、表头 弹窗
  const handleChangeOptionsModal = (
    type: SystemPostStateType['type'],
    record?: SystemPostDataItemType
  ) => {
    state.modalVisible = !state.modalVisible
    state.record = record || {}
    state.type = type
    if (!state.modalVisible) {
      proSaasTableRef.value!?.toSearch() // 更新主列表
      getCategoryDictAjax() // 更新岗位类型
    }
  }

  // 删除
  const handleOpenDeleteConfirm = (record?: SystemPostDataItemType) => {
    if (!record && !proSaasTableRef.value!.selecteds?.length) {
      ElMessage({ type: 'warning', message: '请选择至少一条数据' })
      return
    }
    let params = ''
    if (record?.id) {
      params = record?.id
    } else {
      const element = cloneDeep(proSaasTableRef.value?.selecteds)
      const idsArr = element.map((item: { id: string }) => item.id) // 存待删的id们
      params = idsArr.join(',')
    }
    ElMessageBox.confirm('确定将选择数据删除?', {
      buttonSize: 'small',
      type: 'warning',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(async () => {
        await store.dispatch('systemPost/PostSystemPostRemove', params).then((res) => {
          if (res?.code === 200) {
            proSaasTableRef.value!?.toSearch()
            getCategoryDictAjax() // 更新岗位类型
            ElMessage({ type: 'success', message: '操作成功' })
          } else {
            ElMessage({ type: 'error', message: res?.msg ?? '操作失败' })
          }
        })
      })
      .catch(() => {})
  }

  // 按回车搜索列表
  const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') proSaasTableRef.value!?.toSearch()
  }

  // 清空搜索
  const clearSearchTable = () => {
    if (formValues.postCode === '') {
      delete formValues.postCode // 岗位编号
    }
    if (formValues.postName === '') {
      delete formValues.postName // 岗位名称
    }
    setTimeout(() => {
      proSaasTableRef.value!?.toSearch()
    }, 100)
  }

  const columns: TableColumnProps<SystemPostDataItemType>[] = [
    {
      label: '所属租户',
      prop: 'tenantId',
      minWidth: 180,
      enumValues: systemPostState.tenantSelectEnum,
      showOverflowTooltip: true,
      align: 'center'
    },
    {
      label: '岗位类型',
      prop: 'category',
      minWidth: 180,
      enumValues: systemPostState.categoryEnum,
      showOverflowTooltip: true,
      align: 'center'
    },
    {
      label: '岗位编号',
      prop: 'postCode',
      minWidth: 180,
      showOverflowTooltip: true,
      align: 'center'
    },
    {
      label: '岗位名称',
      prop: 'postName',
      minWidth: 180,
      showOverflowTooltip: true,
      align: 'center'
    },
    {
      label: '是否领导',
      prop: 'leaderPost',
      minWidth: 180,
      enumValues: orderState.appointmentTimeEnum,
      showOverflowTooltip: true,
      align: 'center'
    },
    // { // 是否全局 字段隐藏掉， 默认传0
    //   label: '是否全局',
    //   prop: 'isSystem',
    //   enumValues: orderState.appointmentTimeEnum,
    //   showOverflowTooltip: true,
    //   align: 'center'
    // },
    {
      label: '岗位排序',
      prop: 'sort',
      minWidth: 180,
      showOverflowTooltip: true,
      align: 'center'
    },
    {
      label: '岗位描述',
      prop: 'remark',
      minWidth: 180,
      showOverflowTooltip: true,
      align: 'center'
    },
    {
      label: '操作',
      prop: 'options',
      fixed: 'right',
      unFixed: true,
      minWidth: 180,
      width: 260,
      align: 'center',
      render: ({ row }) => {
        return (
          <>
            {userState.permission.value.has('system_post_view') && (
              <ElLink type="primary" onClick={() => handleChangeOptionsModal('read', row)}>
                <ElIcon>
                  <View />
                </ElIcon>
                &nbsp;查看
              </ElLink>
            )}
            &nbsp;&nbsp;&nbsp;
            {userState.permission.value.has('system_post_update') && (
              <ElLink type="primary" onClick={() => handleChangeOptionsModal('update', row)}>
                <ElIcon>
                  <EditPen />
                </ElIcon>
                &nbsp;编辑
              </ElLink>
            )}
            &nbsp;&nbsp;&nbsp;
            {userState.permission.value.has('system_post_remove') && (
              <ElLink type="primary" onClick={() => handleOpenDeleteConfirm(row)}>
                <ElIcon>
                  <Delete />
                </ElIcon>
                &nbsp;删除
              </ElLink>
            )}
          </>
        )
      }
    }
  ]

  return () => (
    <ElCard>
      <SearchForm
        searchFormProps={{
          model: formValues
        }}
        searchformResponsiveCol={[
          <ElFormItem key="category" prop="category" label="岗位类型：">
            <ElSelect
              v-model={formValues.category}
              placeholder="请选择岗位类型"
              clearable
              onChange={() => {
                proSaasTableRef.value!?.toSearch()
              }}
            >
              {systemPostState.categorySelectList?.value?.map((item: categoryEnum) => (
                <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey!} />
              ))}
            </ElSelect>
          </ElFormItem>,
          <ElFormItem key="postCode" prop="postCode" label="岗位编号：">
            <ElInput
              v-model={formValues.postCode}
              placeholder="请输入岗位编号"
              clearable
              onKeydown={handleKeyDownEnterSubmitForm}
              onClear={clearSearchTable}
            />
          </ElFormItem>,
          <ElFormItem key="postName" prop="postName" label="岗位名称：">
            <ElInput
              v-model={formValues.postName}
              placeholder="请输入岗位名称"
              clearable
              onKeydown={handleKeyDownEnterSubmitForm}
              onClear={clearSearchTable}
            />
          </ElFormItem>
        ]}
        handleSearchList={proSaasTableRef.value?.toSearch}
      />
      <ProSaasTable<SystemPostDataItemType>
        ref={proSaasTableRef}
        columns={columns}
        hasIndex
        hasSelection
        searchParams={{
          postCode: formValues.postCode && handleTrim(formValues.postCode),
          postName: formValues.postName && handleTrim(formValues.postName)
        }}
        searchFormProps={{
          model: formValues
        }}
        dispatchType="systemPost/GetSystemPostList"
        headerTitle={
          <>
            {userState.permission.value.has('system_post_add') && (
              <ElButton type="primary" onClick={() => handleChangeOptionsModal('add')}>
                <ElIcon>
                  <Plus />
                </ElIcon>
                &nbsp; 新增
              </ElButton>
            )}
            {/* // 批量删除 暂隐藏 */}
            {/* <ElButton type="danger" plain onClick={() => handleOpenDeleteConfirm()}>
              <ElIcon>
                <Delete />
              </ElIcon>
              &nbsp; 删除
            </ElButton> */}
          </>
        }
      />
      {state.modalVisible && (
        <SystemPostOptionsModal
          visible={state.modalVisible}
          type={state.type}
          record={state.record}
          onCancel={() => handleChangeOptionsModal('read')}
        />
      )}
    </ElCard>
  )
})
